import axios from 'axios'
import { Toast } from 'vant'
import { getToken, removeToken } from './util'
import qs from 'qs'
axios.defaults.timeout = 10000
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
axios.defaults.baseURL = 'http://qs.letterchain.cn/api'
const ErrorCode = []
axios.interceptors.request.use(config => {
  if (config.method === 'get') {
    config.paramsSerializer = function (params) {
      return qs.stringify(params, { arrayFormat: 'repeat' })
    }
  }
  if (getToken()) {
    config.headers.token = getToken() || ''
  }
  return config
}, error => {
  return Promise.reject(error)
})

axios.interceptors.response.use(response => {
  return response
}, error => {
  if (error) return Promise.resolve(error.response)
  else Promise.reject(error)
})

function checkStatus (response) {
  if (response && (response.status === 200 || response.status === 304 || response.status === 400)) {
    if (response.data) {
      if (response.data.code === 1002 || response.data.code === 1006) {
        removeToken()
        location.href = '/#/login'
        return
      }
    }
    return true
  }
  return false
}

function checkCode (res) {
  return res.code === 0
}

function request (method, url, data, ...rest) {
  data = data || {}
  const bodyStatus = ['post', 'put', 'patch'].indexOf(method) > -1
  const params = bodyStatus ? { data } : { params: data }
  return new Promise((resolve, reject) => {
    axios({
      method,
      url,
      ...params,
      ...rest[0]
    }).then(result => {
      if (checkStatus(result) && checkCode(result.data)) {
        resolve(result.data)
      } else {
        if (!result || ErrorCode.indexOf(result?.data.code) === -1) {
          Toast(result?.data ? (result?.data.msg || '服务优化中') : '服务优化中')
        }
        const resp = result?.data
        reject(resp)
      }
    }).catch((err) => {
      reject(err)
    })
  })
}

export default {
  post (url, params, ...rest) {
    return request('post', url, params, ...rest)
  },
  put (url, params, ...rest) {
    return request('put', url, params, ...rest)
  },
  get (url, params, ...rest) {
    return request('get', url, params, ...rest)
  },
  request (type, url, params, ...rest) {
    return request(type, url, params, ...rest)
  }
}
